import {createStoreBindings} from "mobx-miniprogram-bindings"
import toast from "@vant/weapp/toast/toast"
import {store} from "../../store/store"
import http from "../../utils/request"
Page({
  data: {
    encryptedData:"",
    iv:"",
    showSection:false,
    isLoading:false,
    maxFlag:false
  },
  onLoad(){
    this.storeBindings = createStoreBindings(this,{
      store,
      fields:["showSection","sectionList","toastMessage","activeCategory","blogList","blogViewInfo"],
      actions:["updateShowSection","getSectionList","updateSection","getCategory","setToastMessage","getBlogListByPage","addPage"]
    })
  },
  onShow(){
    if(this.data.toastMessage){//显示回调消息
      toast.success({
        message:this.data.toastMessage,
        duration:1500,
        onClose:()=>{
          this.setToastMessage("")
        }
      })
    }
    if(this.data.sectionList==null){//初始化请求
      new Promise((resolve,reject)=>{
        this.getSectionList(resolve,reject)
      }).then(res=>{
        return new Promise((resolve,reject)=>{
          this.getCategory(resolve,reject)
        })
      }).then(res=>{
        return new Promise((resolve,reject)=>{
          this.getBlogListByPage(resolve,reject)
        })
      }).then(res=>{
      })
    }
    else if(this.data.blogList.length==0||this.data.blogList==null){//返回页面时
      new Promise((resolve,reject)=>{
        this.getBlogListByPage(resolve,reject)
      }).then(res=>{
      })
    }
  },
  onReachBottom(){//触底加载，如果获取数据达到total总数或上一个请求没有完成则不发起请求
    if(this.data.blogList.length>=this.data.blogViewInfo.total){
      this.setData({
        maxFlag:true
      })
    }
    else{
      this.setData({
        maxFlag:false
      })
      if(!this.data.isLoading){
        new Promise((resolve,reject)=>{
          this.setData({
            isLoading:true
          })
          this.addPage(resolve,reject)
        }).then(res=>{
          this.setData({
            isLoading:false
          })
        })
      }
    }
    
  },
  onCloseSectionPopup() {
    this.updateShowSection(false)
  },
  onUpdateSectionHandler(e){
    this.updateSection(e.target.dataset.section)
    this.updateShowSection(false)
  },
  navigateToAddPage(){
    if(!wx.getStorageSync('token')){
      wx.switchTab({
        url: '/pages/user_page/user_page',
        success:()=>{
          this.updateActivePage(3)
        }
      })
    }
    else{
      wx.navigateTo({
        url: '/pages/blog_add_page/blog_add_page',
      })   
  }
  }

})
